﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace FsDump
{
    public partial class MyGpsDump : UserControl
    {
        public delegate void ButtonClickEventHandler(object sender, EventArgs e);
        public event ButtonClickEventHandler ButtonClick;
        Process p;
        String GpsArgs = string.Empty;
        String MsgToPrint=string.Empty;
        bool CanIuPloadTNP = false;
        bool NeedToRegOnDB = false;
        public MyGpsDump()
        {
            
            InitializeComponent();
            this.BT_K.Enabled = false;
            MainClass.SetPortNameValues(this.CBO_COM);
            MainClass.SetGpsNames(this.CBO_GPS);
            int ngps = this.CBO_GPS.Items.Count;
            int ncom = this.CBO_COM.Items.Count;
            string sgps = MainClass.ifr.GetIniValue("INTERFACE", "GPS_" + MainFrm.MyId);
            string scom = MainClass.ifr.GetIniValue("INTERFACE", "COM_" + MainFrm.MyId);

            try
            {
                this.CBO_COM.SelectedIndex = (scom == null ? -1 : Convert.ToInt16(MainClass.ifr.GetIniValue("INTERFACE", "COM_" + MainFrm.MyId)));
            }
            catch
            {
                this.CBO_COM.SelectedIndex = -1;
            }
            try
            {
                this.CBO_GPS.SelectedIndex = (sgps == null ? -1 : Convert.ToInt16(MainClass.ifr.GetIniValue("INTERFACE", "GPS_" + MainFrm.MyId)));
            }
            catch
            {
                this.CBO_GPS.SelectedIndex = -1;
            }
        }
        private void OnButtonClicked(EventArgs e)
        {
            if (ButtonClick != null)
            {
                ButtonClick(this, e);
            }
        }
        private void BT_R_Click(object sender, EventArgs e)
        {
            this.CBO_COM.Items.Clear();
            MainClass.SetPortNameValues(this.CBO_COM);
        }

        private void BT_S_Click(object sender, EventArgs e)
        {
            this.BT_S.Enabled = false;
            this.BT_K.Enabled = true;
            
            if (MsgToPrint != string.Empty) {
                MessageBox.Show(MsgToPrint);
                return;
            }
            GpsArgs = CBO_COM.SelectedItem.ToString() + MainClass.GetGpsNames(CBO_GPS.SelectedIndex);
            if (NeedToRegOnDB) {
                if (!MainClass.IsNumeric(TXT_CIVL.Text))
                {
                    MsgToPrint = "Insert CIVLID";
                }                
                if (TXT_PIL.Text.Trim() == string.Empty && MsgToPrint!=string.Empty) {
                    MsgToPrint = "Insert Pilot Name";
                }

                if (MsgToPrint != string.Empty)
                {
                    MessageBox.Show(MsgToPrint);
                    MsgToPrint = string.Empty;
                    return;
                }
                // register the pilot into DB;
                MainClass.Fs.SetParticipant(int.Parse(TXT_ID.Text.Trim()), TXT_PIL.Text.Trim(), null, null, null, null, false, null, null, int.Parse(TXT_CIVL.Text.Trim()), int.Parse(TXT_ID.Text.Trim()));
                MainClass.Fs.Save();
                if(!MainClass.CheckIDonDB(TXT_ID.Text.Trim())){
                    MessageBox.Show("FAILED TO REGISTER THE PILOT ON FSDB");
                return;
                }
                


            }
            if (MainClass.Mode == 1 ) {
                if (TXT_ID.Text.Trim() != string.Empty)
                {
                    this.StartUplTnp(GpsArgs + " /compid=" + this.TXT_ID.Text.Trim() + " /civlid=" + this.TXT_CIVL.Text.Trim());
                }
                else {
                    this.TXT_STATUS.Text = "Please Fill COMPID";
                }

            }
            if (MainClass.Mode == 0) {
                if (this.TXT_STATUS.Text == "GPS WITH NO ID" && CanIuPloadTNP)
                {
                    this.StartUplTnp(GpsArgs + " /compid=" + this.TXT_ID.Text.Trim() + " /civlid=" + this.TXT_CIVL.Text.Trim());
                }
                else
                {
                    if (SuportDlWpt())
                    {
                        StartDlTnp(GpsArgs);
                    }
                    else 
                    {
                        if (this.TXT_ID.Text.Trim() != string.Empty)
                        {
                            this.StartDlTrk(GpsArgs + " /compid=" + this.TXT_ID.Text.Trim() + " /civlid=" + this.TXT_CIVL.Text.Trim() + " /pilot=" + "\"" + this.TXT_PIL.Text.Trim() + "\"");
                        }
                        else {
                            this.TXT_STATUS.Text = "INSERT COMPID";
                            BT_S.Enabled = true;
                            BT_K.Enabled = false;
                        }
                        }
                }
            }
        }

        private void BT_K_Click(object sender, EventArgs e)
        {
            
            if (p is object) {
                if (!p.HasExited)
                    p.Kill();
            }
            this.BT_K.Enabled = false;
            this.BT_S.Enabled = true;
            this.TXT_CIVL.Text = string.Empty;
            this.TXT_ID.Text = string.Empty;
            this.TXT_PIL.Text = string.Empty;
            this.TXT_STATUS.Text = string.Empty;
            MsgToPrint = string.Empty;
            CanIuPloadTNP = false;
            NeedToRegOnDB = false;
            this.BT_K.Text = "K";    
        }

        private void CBO_GPS_SelectedIndexChanged(object sender, EventArgs e)
        {
            MainClass.ifr.SetIniValue("INTERFACE", "GPS_" + this.Name, CBO_GPS.SelectedIndex.ToString());
        }

        private void CBO_COM_SelectedIndexChanged(object sender, EventArgs e)
        {
            MainClass.ifr.SetIniValue("INTERFACE", "COM_" + this.Name, CBO_COM.SelectedIndex.ToString());
        }
        private void StartDlTnp(string GpsArg) {
            if (File.Exists(MainClass.FlightsPath + "\\" + this.Name + ".txt"))
            {
                File.Delete(MainClass.FlightsPath + "\\" + this.Name + ".txt");
            }
            p = new Process();
            GpsArg = GpsArg + " /notify=" + MainClass.ClassName.ToString() + " /rd_wpt=\"" + MainClass.FlightsPath + "\\" + this.Name + ".txt\" /overwrite /session=" + this.Name + " /win=0 /exit";
            p.Exited += this.EndDlTnp;
            p.EnableRaisingEvents = true;
            p.SynchronizingObject = this;
            p.StartInfo.FileName = MainClass.GpsDumpPath;
            p.StartInfo.Arguments = GpsArg;
            p.Start();
        }
        private void EndDlTnp(object sender, EventArgs e) {
            if (TXT_STATUS.Text.Trim() == "Transfer completed")
            {
                string Tcid = TXT_ID.Text.Trim();
                string Tcivlid = TXT_CIVL.Text.Trim();
                string Tpilot = TXT_PIL.Text.Trim();

                string COMPID = string.Empty;
                string[] CID=MainClass.SearchOnWaypoints("COMPID", MainClass.FlightsPath + "\\" + this.Name + ".txt",this.CBO_GPS.SelectedIndex);
               if(CID.Length>1){
                   MessageBox.Show("This GPS " + this.CBO_GPS.SelectedText + " on "+ this.CBO_COM.SelectedText + " have " + CID.Length + "\n COMPID You Must Erase all of them and Reupload the COMPID");
                   return;
               }
               if (CID.Length == 1)
                   COMPID = CID[0];
               else
                   COMPID = string.Empty;
                if (Tcid!=string.Empty && COMPID != Tcid) {
                    this.StartUplTnp(GpsArgs + " /compid=" + Tcid + " /civlid=" + Tcivlid );
                    return;
                }
                if (COMPID != string.Empty)
                {
                    if (MainClass.CheckIDonDB(COMPID))
                    {
                        string[] Pilot = MainClass.SearchForCOMPIDonDB(COMPID);
                        this.TXT_ID.Text = Pilot[0];
                        this.TXT_CIVL.Text = Pilot[1];
                        this.TXT_PIL.Text = Pilot[2];
                        if (MainClass.wasdownloaded(COMPID))
                        {
                            this.TXT_STATUS.Text = "PILOT ALLREADY PROCESSED";
                        }
                        else
                        {
                            File.Copy(MainClass.FlightsPath + "\\" + this.Name + ".txt", MainClass.FlightsPath + "\\" + COMPID + ".wpt",true);
                            this.TXT_STATUS.Text = "DOWNLOADING TRAKLOGS";
                            this.StartDlTrk(GpsArgs + " /compid=" + this.TXT_ID.Text.Trim() + " /civlid=" + this.TXT_CIVL.Text.Trim() + " /pilot=" + "\"" + this.TXT_PIL.Text.Trim() + "\"");
                        }
                    }
                    else
                    {
                        this.TXT_ID.Text = COMPID;
                        this.TXT_STATUS.Text = "NOT REG. UPLOADING TNP";
                        // UPLOAD TURNPOINTS to GPS;
                    }
                }
                else {
                    this.TXT_STATUS.Text = "GPS WITH NO ID";
                }

            }

        }
        private void StartDlTrk(string GpsArg) {
            p = new Process();
            if (MainClass.Usefilter == true) {
                //YYYYMMDDhhmmss
                string F = (MainClass.FilterTime.AddHours(-1*(double)MainClass.Utcdiff)).ToString("yyyMMddHHmmss");
                GpsArg = GpsArg + " /filter=" + F;
            }
            if (MainClass.Poff == true) {
                GpsArg = GpsArg + " /pwroff";
            }
            GpsArg = GpsArg + " /comp_dir=\"" + MainClass.FlightsPath + "\" /notify=" + MainClass.ClassName.ToString() + " /nosplit /nocheck  /comp_log=igc  /overwrite /session=" + this.Name + " /win=0 /exit";
            p.Exited += this.EndDlTrk;
            p.EnableRaisingEvents = true;
            p.SynchronizingObject = this;
            p.StartInfo.FileName = MainClass.GpsDumpPath;
            p.StartInfo.Arguments = GpsArg;
            p.Start();
        }
        private void EndDlTrk(object sender, EventArgs e) {
            OnButtonClicked(e);
            this.BT_S.Enabled = true;
            this.BT_K.Enabled = true;
            this.BT_K.Text = "ok";
        }
        private void StartUplTnp(string GpsArg) {
            p = new Process();
            if (MainClass.Mode == 1) {
               // GpsArg = GpsArg + " /pwroff ";
                if (MainClass.Poff == true)
                {
                    GpsArg = GpsArg + " /pwroff";
                }
            }
            if (this.CBO_GPS.SelectedIndex == 1)
            {
                GpsArg = GpsArg + " /notify=" + MainClass.ClassName.ToString() + " /wr_wpt2=\"" + MainClass.TnpPath + "\"" + " /session=" + this.Name + " /win=0 /exit";
            }
            else
            {
                GpsArg = GpsArg + " /notify=" + MainClass.ClassName.ToString() + " /wr_wpt=\"" + MainClass.TnpPath + "\"" + " /session=" + this.Name + " /win=0 /exit";
            }

            p.Exited += this.EndUplTnp;
            p.EnableRaisingEvents = true;
            p.SynchronizingObject = this;
            p.StartInfo.FileName = MainClass.GpsDumpPath;
            p.StartInfo.Arguments = GpsArg;
            p.Start();
        
        }
        private void EndUplTnp(object sender, EventArgs e) {
            if (MainClass.Mode == 0)
            {
                this.StartDlTnp(GpsArgs);
            }
            if (MainClass.Mode == 1) {
                this.BT_K.Enabled = false;
                this.BT_R.Enabled = true;
                this.BT_S.Enabled = true;
                
                this.TXT_ID.Text = string.Empty;
            }
        }
        private bool SuportDlWpt()
        {
            string[] gindex = { "0", "1", "6" };
            string[] cboind = { CBO_GPS.SelectedIndex.ToString() };
            if (MainClass.InArray(gindex, cboind) >= 0)
                return true;
            else
                return false;
        }

        private void TXT_ID_TextChanged(object sender, EventArgs e)
        {
            MsgToPrint = string.Empty;
            if (!MainClass.IsNumeric(this.TXT_ID.Text) && this.TXT_ID.Text != string.Empty)
            {
                this.TXT_ID.Text = string.Empty;
                this.TXT_CIVL.Text = string.Empty;
                this.TXT_PIL.Text = string.Empty;
                this.MsgToPrint = "ONLY NUMERIC FOR COMPID";
                CanIuPloadTNP = false;
                NeedToRegOnDB = false;
                return;
            }
            if (MainClass.CheckIDonDB(this.TXT_ID.Text))
            {
                string[] Pilot = MainClass.SearchForCOMPIDonDB(this.TXT_ID.Text);
                this.TXT_ID.Text = Pilot[0];
                this.TXT_CIVL.Text = Pilot[1];
                this.TXT_PIL.Text = Pilot[2];
                CanIuPloadTNP = true;
                NeedToRegOnDB = false;
                return;
            }
            else {
                string[] Pilot = MainClass.SearchForCOMPIDonDB(this.TXT_ID.Text);
                this.TXT_ID.Text = Pilot[0];
                this.TXT_CIVL.Text = Pilot[1];
                this.TXT_PIL.Text = Pilot[2];
                NeedToRegOnDB = true;
                CanIuPloadTNP = true;
                return;
            }
        }

        private void TXT_STATUS_TextChanged(object sender, EventArgs e)
        {
            if (this.TXT_STATUS.Text == "GPS WITH NO ID") {
                this.BT_S.Enabled = true;
            }
        }
    }
}
